from mttkinter import mtTkinter as tk
import tkinter.messagebox 
import pickle
from tkinter import scrolledtext
import socket
import threading
from datetime import datetime

window = tk.Tk()
window.title("小A君")
window.geometry("500x500")

#welcome image
canvas = tk.Canvas(window,bg="white",height=500,width=500)
image_file = tk.PhotoImage(file="E:\\python程序\\GUI系列\\insout.gif")
image = canvas.create_image(100,10,anchor="nw",image=image_file)

#welcome image
image_file1 = tk.PhotoImage(file="E:\\python程序\\GUI系列\\welout.gif")
image = canvas.create_image(100,350,anchor="nw",image=image_file1)
canvas.pack()

#user information
tk.Label(window,text="User name: ").place(x=50,y=250)
tk.Label(window,text="Password: ").place(x=50,y=290)
var_user_name = tk.StringVar()
var_user_name.set("Example@python")
entry_user_name = tk.Entry(window,textvariable=var_user_name)
entry_user_name.place(x=160,y=250)
var_user_pwd = tk.StringVar()
entry_user_pwd = tk.Entry(window,textvariable=var_user_pwd,show="*")
entry_user_pwd.place(x=160,y=290)

#login and sign up button
def user_login():
    user_name =  var_user_name.get()
    user_pwd = var_user_pwd.get()
    try:
        with open("users_info.pickle","rb") as user_file:
            users_info = pickle.load(user_file)
    except FileNotFoundError:
        with open("users_info.pickle","wb") as user_file:
            users_info = {"admin":"admin"}
            pickle.dump(users_info,user_file)
    if user_name in users_info:
        if user_pwd == users_info[user_name]:
            def tcp_recv(sock):
                while True:
                    str = sock.recv(1024).decode("utf-8")
                    show_info(str)

            def send_func(sock):
                str = send_msg.get("0.0", "end")
                sock.send(str.encode("utf-8"))
                show_info(str)
            
            def show_info(str):
                now = datetime.now()
                s_time = now.strftime("%Y-%m-%d %H:%M:%S")
                str = str.rstrip()
                if len(str) == 0:
                    return -1
                send_msg.delete("0.0", "end")
                temp = s_time + "\n    " + str + "\n"
                show_msg.insert(tk.INSERT, "%s" % temp)
                
            msFont = '微软雅黑' #字体
            fontSize = 18 #字体大小
            sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            sock.connect(("127.0.0.1",8888))
            
            mainWindow = tk.Tk()
            mainWindow.title(user_name)
            mainWindow.minsize(400,400)
            show_msg = scrolledtext.ScrolledText(mainWindow,font=(msFont,fontSize))
            show_msg.place(width=400,height=250,x=0,y=0)
            
            send_msg = scrolledtext.ScrolledText(mainWindow,font=(msFont,fontSize))
            send_msg.place(width=400,height=140,x=0,y=260)
            button_send = tk.Button( mainWindow, font=(msFont,fontSize),text = "发  送",bg="orange",fg="white",
                                    command=lambda:send_func(sock))
            button_send.place(width=100,height=40,x=300,y=360)
            
            t = threading.Thread(target=tcp_recv,args=(sock,))
            t.start()
            tk.mainloop()
        else:
            tkinter.messagebox.showerror(message="Sorry,your password is wrong.Try again")
    else:
        is_sign_up = tkinter.messagebox.askyesno("welcome,you have not sign up yet.Sign up now???")
        
        if is_sign_up:
            user_sign_up()

def user_sign_up():
    
    def sign_to_Mofan_python():
        np = new_pwd.get() 
        npf = new_pwd_confirm.get()
        nn = new_name.get()
        with open("users_info.pickle","rb") as user_file:
            exist_user_info = pickle.load(user_file)
        if np != npf:
            tk.messagebox.showerror("Sorry,Password and confirm password must be the same!!!")
        elif nn in exist_user_info:
            tk.messagebox.showerror("Sorry,the user has already signed up!!!")
        else:
            exist_user_info[nn] = np
            with open("users_info.pickle","wb") as user_file:
                pickle.dump(exist_user_info,user_file)
            tk.messagebox.showinfo("welcome,you have successfully sign up!!!")
            window_sign_up.destroy()

    window_sign_up = tk.Toplevel(window)
    window_sign_up.geometry("350x200")
    window_sign_up.title("Sign up window")

    new_name = tk.StringVar()
    new_name.set("example@python")
    tk.Label(window_sign_up,text="User name: ").place(x=10,y=10)
    entry_new_name = tk.Entry(window_sign_up,textvariable=new_name)
    entry_new_name.place(x=150,y=10)

    new_pwd = tk.StringVar()
    tk.Label(window_sign_up,text="Password: ").place(x=10,y=50)
    entry_user_pwd = tk.Entry(window_sign_up,textvariable=new_pwd,show="*")
    entry_user_pwd.place(x=150,y=50)

    new_pwd_confirm = tk.StringVar()
    tk.Label(window_sign_up,text="Confirm password: ").place(x=10,y=90)
    entry_user_pwd_confirm = tk.Entry(window_sign_up,textvariable=new_pwd_confirm,show="*")
    entry_user_pwd_confirm.place(x=150,y=90)

    btn_confirm_sign_up = tk.Button(window_sign_up,text="Sign up",command=sign_to_Mofan_python)
    btn_confirm_sign_up.place(x=150,y=130)

btn_login = tk.Button(window,text="Login",command=user_login)
btn_login.place(x=170,y=320)
btn_sign_up = tk.Button(window,text="Sign_up",command=user_sign_up)
btn_sign_up.place(x=270,y=320)

window.mainloop()
'''不断循环刷新'''